package com.dm.cloud.databases.mutimysql;

import lombok.extern.log4j.Log4j2;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
  * @author zhangdm
  * @Description: 动态数据源实现类
  * @return
  * @throws
  */
@Log4j2
public class DynamicDataSource extends AbstractRoutingDataSource {

    /** 数据源路由，此方法用于产生要选取的数据源逻辑名称 */
    @Override
    protected Object determineCurrentLookupKey() {
        Map<Object, DataSource> dataMap = getResolvedDataSources();

        if (dataMap.containsKey(JdbcContextHolder.getDataSource())) {
            log.info(">>> current thread " + Thread.currentThread().getName() + " add database【 " + JdbcContextHolder.getDataSource() + " 】 to ThreadLocal");
        } else {
            log.info(">>> current thread " + Thread.currentThread().getName() + " is working with 【default】 database");
        }
        //从共享线程中获取数据源名称
        return JdbcContextHolder.getDataSource();
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
    }
}